package cn.jy.careuplusdoctor.utils;

import java.security.SecureRandom;
import java.util.Random;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import android.util.Base64;

public class DesTool4Android {
	

	public static byte[] desCrypto(byte[] datasource, String password)

	{

		try

		{

			SecureRandom random = new SecureRandom();

			DESKeySpec desKey = new DESKeySpec(password.getBytes());


			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");

			SecretKey securekey = keyFactory.generateSecret(desKey);



			Cipher cipher = Cipher.getInstance("DES");



			cipher.init(Cipher.ENCRYPT_MODE, securekey, random);



			return cipher.doFinal(datasource);

		}

		catch (Throwable e)

		{

			e.printStackTrace();

		}

		return null;

	}

	public static byte[] decrypt(byte[] src, String password)

	throws Exception

	{
		SecureRandom random = new SecureRandom();
		DESKeySpec desKey = new DESKeySpec(password.getBytes());
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey securekey = keyFactory.generateSecret(desKey);
		Cipher cipher = Cipher.getInstance("DES");
		cipher.init(Cipher.DECRYPT_MODE, securekey, random);
		return cipher.doFinal(src);

	}
	
	public static String encrypt(String data, String key) throws Exception {
		byte[] result = desCrypto(data.getBytes(), key);
		byte[] mString64 = Base64.encode(result, Base64.DEFAULT);//����
		String strs =new String(mString64);
		return strs;
	}

		public static String getPass() {
			StringBuffer str = new StringBuffer();
			for (char i = 'a'; i < 'z'; i++) {
				str.append(i);
			}
			for (char i = 'A'; i < 'Z'; i++) {
				str.append(i);
			}
			for (int i = 0; i < 10; i++) {
				str.append(i);
			}
			Random rd = new Random();
			String result = "";

			for (int i = 0; i < 8; i++) {
				result += str.charAt(rd.nextInt(str.length()));
			}
			return result;
		}


		public static String reSort1(String sc, String pass) {// 
			Random r = new Random();
			int i = r.nextInt(pass.length() - 1) + 1;
			String a = pass.substring(0, i);
			String b = pass.substring(i, pass.length());
			return sc + i + b + a;//
		}
	

	

	public static String getToken(String num,String content) throws Exception {
		String data = num+"/"+content+"/careu";
		String key = getPass();
		String token = reSort1(encrypt(data, key), key);
		return token;
	}
	

	public static String getToken() throws Exception {
		String data = "careu-version2.0";
		String key = getPass();
		String token = reSort1(encrypt(data, key), key);
		return token;
	}
}
